﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ElementumForever.Interfaces;
using ElementumForever.Utility;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using ElementumForever.CommandPattern;
using ElementumForever.Editer;

namespace ElementumForever.Decorators
{
    class DragDecorator : BaseUIDecorator
    {
        bool _mousePress = false;
        Vector2 mouseOffset = new Vector2();
        Vector2 oldP = new Vector2();
        MainFormModel _formModel;

        public DragDecorator(BaseEntity master, MainFormModel _formModel)
            : base(master)
        {
            this._formModel = _formModel;
        }

        public override void OnMouseDown(MouseState state)
        {
            base.OnMouseDown(state);
            if (state.LeftButton == ButtonState.Pressed)
            {
                Vector2 mp = UnitHelper.ToVector2(state.X, state.Y);
                //Vector2 mp2 = CoordinateHelper.FromScreenToScene(mp, _component.Parent);
                mouseOffset = new Vector2(_component.X, _component.Y) - CoordinateHelper.FromScreenToScene(mp,_component.Parent);
                _mousePress = _component.IsContain(mp);
                if (_mousePress)
                {
                    onBeginDrag(_component.X, _component.Y);
                }
            }
        }

        public override void OnMouseUp(Microsoft.Xna.Framework.Input.MouseState state)
        {
            base.OnMouseUp(state);
            if (state.LeftButton == ButtonState.Released && _mousePress)
            {
                _mousePress = false;
                onEndDrag(_component.X, _component.Y);
            }
        }

        private void onBeginDrag(float oldX, float oldY)
        {
            oldP.X = oldX;
            oldP.Y = oldY;
        }

        private void onEndDrag(float newX, float newY)
        {
            if (oldP.X != newX || oldP.Y != newY)
            {
                ChangeXYCommand command = new ChangeXYCommand(_component, oldP.X, newX, oldP.Y, newY);
                _formModel.AddCommand(command);
                Console.WriteLine("drag:" + oldP + ";" + newX + "," + newY);
            }
        }

        public override void OnMouseMove(Microsoft.Xna.Framework.Input.MouseState state)
        {
            base.OnMouseMove(state);
            //Console.WriteLine("_mousePress" + _mousePress);
            //Console.WriteLine("IsSelect" + IsSelect);

            Vector2 mp = UnitHelper.ToVector2(state.X, state.Y);
            mp = CoordinateHelper.FromScreenToScene(mp, _component.Parent);

            if (_mousePress && IsSelect)
            {
                _component.X = mp.X + mouseOffset.X;
                _component.Y = mp.Y + mouseOffset.Y;
            }
        }

    }
}
